<template>
  <div class="login-container">
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
      auto-complete="off"
      label-position="left"
    >
      <div class="title-container">
        <h3 class="title">Login Form</h3>
      </div>

      <el-form-item prop="phoneNumber">
        <span class="svg-container">
          <i class="iconfont icon-yonghu"></i>
        </span>
        <el-input
          ref="phoneNumber"
          v-model="loginForm.phoneNumber"
          placeholder="请输入手机号"
          name="phoneNumber"
          type="text"
          tabindex="1"
          auto-complete="off"
        />
      </el-form-item>

      <el-form-item prop="password">
        <span class="svg-container">
          <i class="iconfont icon-suoding"></i>
        </span>
        <el-input
          :key="passwordType"
          ref="password"
          v-model="loginForm.password"
          :type="passwordType"
          placeholder="请输入密码"
          name="password"
          tabindex="2"
          auto-complete="off"
          @keyup.enter.native="handleLogin"
        />
        <span class="show-pwd" @click="showPwd">
          <i
            class="iconfont"
            :class="[
              passwordType === 'password'
                ? 'icon-yincangbukejian'
                : 'icon-xianshikejian',
            ]"
          ></i>
        </span>
      </el-form-item>
      <el-form-item prop="code" class="code">
        <el-input
          ref="code"
          v-model="loginForm.code"
          placeholder="请输入验证码"
          name="code"
          type="text"
          tabindex="1"
          class="code-input"
          auto-complete="off"
        />
        <el-button v-if="!sending" class="code-handle" @click="getCode(0)"
          >获取验证码</el-button
        >
        <el-button v-else disabled key="disabled" class="code-handle disabled">
          {{ leftSecond }}秒后重发
        </el-button>
        <div v-if="sending" class="code-img" @click="getCode(1)">
          <img :src="codeImg" alt="" />
        </div>
      </el-form-item>
      <el-button
        :loading="loading"
        type="primary"
        style="width: 100%; margin-bottom: 30px"
        @click.native.prevent="handleLogin"
        >登录</el-button
      >
    </el-form>
  </div>
</template>

<script>
export default {
  name: "Login",
  data() {
    // const checkPhone = (rule, value, callback) => {
    //   value = value.trim();
    //   let reg_tel =
    //     /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
    //   if (value === "") {
    //     this.loginForm.phoneNumber = "";
    //     callback(new Error("手机号码不能为空!"));
    //   } else if (!reg_tel.test(value)) {
    //     callback(new Error("请正确填写您的手机号码!"));
    //   } else {
    //     callback();
    //   }
    // };
    // const validatePassword = (rule, value, callback) => {
    //   value = value.trim();
    //   if (value === "") {
    //     this.loginForm.password = "";
    //     callback(new Error("密码长度不能为空!"));
    //   } else if (value.length < 6) {
    //     callback(new Error("密码长度不能小于6位数!"));
    //   } else {
    //     callback();
    //   }
    // };
    const checkCode = (rule, value, callback) => {
      if (value.trim() === "") {
        this.loginForm.code = "";
        callback(new Error("请输入验证码"));
      } else {
        callback();
      }
    };
    return {
      loginForm: {
        phoneNumber: "00001",
        password: "admin@123456",
        code: "",
        key: "",
      },
      loginRules: {
        // phoneNumber: [{ validator: checkPhone, trigger: "blur" }],
        // password: [{ validator: validatePassword, trigger: "blur" }],
        code: [{ validator: checkCode, trigger: "blur" }],
      },
      codeImg: "",
      loading: false,
      getcode: "获取验证码",
      leftSecond: 0,
      sending: false,
      passwordType: "password",
      redirect: undefined,
    };
  },
  methods: {
    // 是否显示密码
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },
    // 登录
    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.$store
            .dispatch("login", this.loginForm)
            .then((res) => {
              console.log(res);
              // this.$router.push({ path: this.redirect || "/" });
              // this.$router.push({ path: "/" });
              this.$message.success("登录成功!");
              this.$router.push("/");
              this.loading = false;
            })
            .catch((err) => {
              this.loading = false;
              this.$message.error(err);
            });
        } else {
          return false;
        }
      });
    },
    // 验证码
    getCode(type) {
      if (type == 0) {
        try {
          let user = this.loginForm.phoneNumber;
          if (user) {
            this.$store
              .dispatch("getCode")
              .then((res) => {
                this.$message.success("获取成功!");
                console.log(res);
                this.codeImg = res.captcha;
                console.log(res.key);
                this.loginForm.key = res.key;
                //倒计时
                this.sending = true;
                // this.leftSecond = 10;
                this.leftSecond = 60;
                // 防止频繁点击影响定时器
                if (this.timer) {
                  clearInterval(this.timer);
                }
                //创建定时器
                this.timer = setInterval(() => {
                  //计数器减一
                  this.leftSecond--;
                  if (this.leftSecond <= 0) {
                    //停止定时器
                    clearInterval(this.timmer);
                    //还原计数器
                    this.leftSecond = 0;
                    //还原按钮状态
                    this.sending = false;
                    //将组件的code属性值变为仓库中验证码[验证码直接自己填写了]
                    // console.log(this.$store.state.user.code);
                  }
                }, 1000);
              })
              .catch((err) => {
                this.$message.error("获取失败");
              });
          } else {
            this.$message.error("请输入手机号");
          }
        } catch (error) {
          alert(error.message);
        }
      } else {
        this.$store
          .dispatch("getCode")
          .then((res) => {
            this.codeImg = res.captcha;
            this.loginForm.key = res.key;
          })
          .catch((err) => {
            this.$message.error("获取失败");
          });
      }
    },
  },
  beforeDestroy() {
    //清除定时器
    clearInterval(this.timer);
  },
};
</script>
<style lang="scss">
$bg: #283443;
$light_gray: #fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  background-image: url("~@/assets/image/bj2.jpg");
  background-size: 100% 100%;

  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      // -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;

  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    // overflow: hidden;
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .iconfont {
    font-size: 24px;
  }

  .code {
    position: relative;

    .code-input {
      display: inline-block;
      width: 75%;
    }

    .code-handle {
      position: absolute;
      height: 100%;
      width: 112px;
      background: rgba(0, 0, 0, 0);
      border: none;
      border: 1px solid rgba(255, 255, 255, 0.1);
      border-radius: 5px;
      color: #409eff;
    }

    .code-img {
      position: absolute;
      top: 0;
      right: -138px;
      // border: 1px solid rgba(255, 255, 255, 0.1);
      // border-radius: 5px;
    }
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}
</style>
